package com.luxondata.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;

import com.luxondata.exception.InvalidApiKeyException;
import com.luxondata.module.system.entry.User;
import com.luxondata.module.system.service.UserService;

public class ApiKeyAuthenticationProvider implements AuthenticationProvider {

	@Autowired
	private UserService userService;
	
	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {

		String apiKey = (String)authentication.getCredentials();
		User user = userService.findByApiKey(apiKey);
		if (user!=null){
			return new PreAuthenticatedAuthenticationToken(user,apiKey,user.getAuthorities());
		} else {
			throw new InvalidApiKeyException("Fail to authenticate with api key: " + apiKey);
		}
	}

	@Override
	public boolean supports(Class<?> authentication) {
		 return
		authentication.isAssignableFrom(
			        PreAuthenticatedAuthenticationToken.class)||
			      authentication.isAssignableFrom(
			    		  ApiKeyAuthenticationProvider.class);	
	}
}